package cn.thornbird.orgsync.helper.token;

import cn.thornbird.orgsync.helper.DingTalkHelper;
import cn.thornbird.orgsync.model.certificate.DingTalkCertificate;
import cn.thornbird.orgsync.model.dingtalk.Token;
import cn.thornbird.orgsync.util.JsonUtil;

import java.util.HashMap;
import java.util.Map;

public class DingTalkToken extends AccessToken<DingTalkCertificate> {

    public DingTalkToken(String certificateText) {
        super(certificateText);
        Map<String, Object> map = JsonUtil.parseMap(certificateText);
        DingTalkCertificate certificate = new DingTalkCertificate();
        certificate.setAppKey(map.get("appKey").toString());
        certificate.setAppSecret(map.get("appSecret").toString());
        this.certificate = certificate;
    }

    @Override
    protected String acquireToken() {
        String token = INVALID_TOKEN_TEXT;
        DingTalkHelper helper = new DingTalkHelper();
        helper.initialize(null, certificateText);
        Map<String, Object> uriVariables = new HashMap<>();
        uriVariables.put("appkey", certificate.getAppKey());
        uriVariables.put("appsecret", certificate.getAppSecret());
        long now = System.currentTimeMillis();
        Token result = helper.doGet(DingTalkHelper.GET_TOKEN_PATH, uriVariables, null, Token.class);
        if (result != null && result.isSuccess()) {
            token = result.getAccessToken() + "," + (now + result.getExpiresIn() * 1000 + EXPIRATION_DELTA);
        }
        return token;
    }

}
